﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WebApiThrottle;

namespace HCQ2WebAPI_Logic.Filters
{
    /// <summary>
    ///  限流过滤器
    /// </summary>
    public class CustomThrottlingFilter : ThrottlingFilter
    {
        /// <summary>
        /// Sets the indentity.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>RequestIdentity.</returns>
        protected override RequestIdentity SetIdentity(HttpRequestMessage request)
        {
            var sessionId = string.Empty;
            try
            {
                var requestCookie = request.Headers.GetCookies().FirstOrDefault();
                if (requestCookie != null)
                {
                    foreach (var item in requestCookie.Cookies.Where(item => item.Name == "Session_Id"))
                    {
                        sessionId = item.Value;
                        break;
                    }
                }
            }
            catch (Exception)
            {
                sessionId = string.Empty;
            }
            return new RequestIdentity()
            {
                ClientKey = string.IsNullOrWhiteSpace(sessionId) ? sessionId : "anon",
                ClientIp = base.GetClientIp(request).ToString(),
                Endpoint = request.RequestUri.AbsolutePath.ToLowerInvariant()
            };
        }
    }
}